package net.sudot.chess.business.dao;

import net.sudot.chess.business.dto.CustomerDetailDTO;
import net.sudot.chess.business.model.Customer;
import net.sudot.chess.business.model.InviteRecord;
import org.springframework.stereotype.Repository;

import javax.persistence.TypedQuery;
import java.time.Instant;
import java.util.List;

/**
 * 邀请记录
 *
 * @author tangjialin on 2018-03-25.
 */
@Repository
public class InviteRecordDao extends BaseDao<InviteRecord> {

    /**
     * 获取被邀请者的邀请人信息
     *
     * @param invitee 被邀请者的用户主键
     * @return 返回用户的邀请人信息
     */
    public Customer findByInvitee(Long invitee) {
        String ql = "SELECT customer FROM Customer customer" +
                " INNER JOIN InviteRecord inviteRecord ON customer.id = inviteRecord.inviter" +
                " WHERE inviteRecord.invitee = :invitee";
        TypedQuery<Customer> query = entityManager.createQuery(ql, Customer.class);
        query.setParameter("invitee", invitee);
        return uniqueResult(query);
    }

    /**
     * 获取邀请者邀请的用户和其周期内的充值金额
     *
     * @param inviter 邀请者的用户主键
     * @param start   起始时间
     * @param end     结束时间
     * @return 返回邀请者邀请的用户和其周期内的充值金额
     */
    public List<CustomerDetailDTO> findListByInviter(Long inviter, Instant start, Instant end) {
        String ql = "SELECT new net.sudot.chess.business.dto.CustomerDetailDTO(customer.id, customer.nickname, customer.head, SUM(orderRecharge.paymentAmount), customer.createdDate)" +
                " FROM Customer customer" +
                " INNER JOIN InviteRecord inviteRecord ON inviteRecord.invitee = customer.id" +
                " LEFT JOIN OrderRecharge orderRecharge ON orderRecharge.userId = inviteRecord.invitee AND orderRecharge.completeDate >= :start AND orderRecharge.completeDate < :end" +
                " WHERE inviteRecord.inviter = :inviter" +
                " GROUP BY customer.id" +
                " ORDER BY SUM(orderRecharge.paymentAmount) DESC, customer.createdDate DESC";
        TypedQuery<CustomerDetailDTO> query = entityManager.createQuery(ql, CustomerDetailDTO.class);
        query.setParameter("inviter", inviter);
        query.setParameter("start", start);
        query.setParameter("end", end);
        return query.getResultList();
    }
}
